<html><head><meta charset="utf-8"><title>19 使用 Webpack 的 splitChunks 功能来拆分代码-慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">

<div class="container clearfix" id="top" style="display: block; width: 1134px;">
    
    <div class="center_con js-center_con l" style="width: 1134px;">
        <div class="article-con">
                            <!-- 买过的阅读 -->
                <div class="map">
                    <a href="/read" target="_blank"><i class="imv2-feather-o"></i></a>
                    <a href="/read/29" target="_blank">Webpack 从零入门到工程化实战</a>
                    <a href="" target="_blank">
                        <span>
                            / 3-3 19 使用 Webpack 的 splitChunks 功能来拆分代码
                        </span>
                    </a>
                </div>

            


            <div class="art-title" style="margin-top: 0px;">
                19 使用 Webpack 的 splitChunks 功能来拆分代码
            </div>
            <div class="art-info">
                
                <span>
                    更新时间：2019-06-24 09:31:37
                </span>
            </div>
            <div class="art-top">
                                <img src="https://img3.mukewang.com/5cd963fc000167cb06400360.jpg" alt="">
                                                <div class="famous-word-box">
                    <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                    <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                    <div class="famous-word">读一本好书，就是和许多高尚的人谈话。<p class="author">——歌德</p></div>
                </div>
                            </div>
            <div class="art-content js-lookimg">
                <div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在 Webpack4 之前，我们处理公共模块的方式都是使用 CommonsChunkPlugin，然后该插件让开发配置繁琐，并且使公共代码的抽离不够彻底和细致，因此新的<code>splitChunks</code>改进了这些能力，不过虽然<code>splitChunks</code>相对 CommonsChunkPlugin 进步不少，但是 splitChunks 的配置却比较复杂。</p>
</div><div class="cl-preview-section"><h2 id="webpack-代码拆分方式" style="font-size: 30px;">Webpack 代码拆分方式</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在 Webpack 中，总共提供了三种方式来实现代码拆分（Code Splitting）：</p>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;">entry 配置：通过多个 entry 文件来实现；</li>
<li style="font-size: 20px; line-height: 38px;">动态加载（按需加载）：通过写代码时主动使用<code>import()</code>或者<code>require.ensure</code>来动态加载；</li>
<li style="font-size: 20px; line-height: 38px;">抽取公共代码：使用<code>splitChunks</code>配置来抽取公共代码。</li>
</ul>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这里我们主要讲的是通过<code>splitChunks</code>抽取公共代码。在讲解之前，再来复习下 Webpack 中三个重要的概念：<code>module</code>、<code>chunks</code>、<code>bundle</code>。</p>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;">module：就是 JavaScript 的模块，简单来说就是你通过 <code>import</code>、<code>require</code> 语句引入的代码，也包括 css、图片等资源；</li>
<li style="font-size: 20px; line-height: 38px;">chunk: chunk 是 webpack 根据功能拆分出来的，chunk 包含着 module，可能是一对多也可能是一对一，chunk 包含三种情况，就是上面介绍的三种实现代码拆分的情况。</li>
<li style="font-size: 20px; line-height: 38px;">bundle：bundle 是 webpack 打包之后的各个文件，一般就是和 chunk 是一对一的关系，bundle 就是对 chunk 进行编译压缩打包等处理之后的产出。</li>
</ul>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">记住这些，后面会用到，下面开始 splitChunks 配置。</p>
</div><div class="cl-preview-section"><h2 id="splitchunks-默认配置" style="font-size: 30px;">splitChunks 默认配置</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">由于 Webpack 做到了开箱即用，所以<code>splitChunks</code>是有<a href="https://github.com/webpack/webpack/blob/master/lib/WebpackOptionsDefaulter.js">默认配置</a>的：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js">module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment">// ...</span>
    optimization<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        splitChunks<span class="token punctuation">:</span> <span class="token punctuation">{</span>
            chunks<span class="token punctuation">:</span> <span class="token string">'async'</span><span class="token punctuation">,</span> <span class="token comment">// 三选一： "initial" | "all" | "async" (默认)</span>
            minSize<span class="token punctuation">:</span> <span class="token number">30000</span><span class="token punctuation">,</span> <span class="token comment">// 最小尺寸，30K，development 下是10k，越大那么单个文件越大，chunk 数就会变少（针对于提取公共 chunk 的时候，不管再大也不会把动态加载的模块合并到初始化模块中）当这个值很大的时候就不会做公共部分的抽取了</span>
            maxSize<span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token comment">// 文件的最大尺寸，0为不限制，优先级：maxInitialRequest/maxAsyncRequests &lt; maxSize &lt; minSize</span>
            minChunks<span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token comment">// 默认1，被提取的一个模块至少需要在几个 chunk 中被引用，这个值越大，抽取出来的文件就越小</span>
            maxAsyncRequests<span class="token punctuation">:</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token comment">// 在做一次按需加载的时候最多有多少个异步请求，为 1 的时候就不会抽取公共 chunk 了</span>
            maxInitialRequests<span class="token punctuation">:</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token comment">// 针对一个 entry 做初始化模块分隔的时候的最大文件数，优先级高于 cacheGroup，所以为 1 的时候就不会抽取 initial common 了</span>
            automaticNameDelimiter<span class="token punctuation">:</span> <span class="token string">'~'</span><span class="token punctuation">,</span> <span class="token comment">// 打包文件名分隔符</span>
            name<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token comment">// 拆分出来文件的名字，默认为 true，表示自动生成文件名，如果设置为固定的字符串那么所有的 chunk 都会被合并成一个</span>
            cacheGroups<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                vendors<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                    test<span class="token punctuation">:</span> <span class="token regex">/[\\/]node_modules[\\/]/</span><span class="token punctuation">,</span> <span class="token comment">// 正则规则，如果符合就提取 chunk</span>
                    priority<span class="token punctuation">:</span> <span class="token operator">-</span><span class="token number">10</span> <span class="token comment">// 缓存组优先级，当一个模块可能属于多个 chunkGroup，这里是优先级</span>
                <span class="token punctuation">}</span><span class="token punctuation">,</span>
                <span class="token keyword">default</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>
                    minChunks<span class="token punctuation">:</span> <span class="token number">2</span><span class="token punctuation">,</span>
                    priority<span class="token punctuation">:</span> <span class="token operator">-</span><span class="token number">20</span><span class="token punctuation">,</span> <span class="token comment">// 优先级</span>
                    reuseExistingChunk<span class="token punctuation">:</span> <span class="token boolean">true</span> <span class="token comment">// 如果该chunk包含的modules都已经另一个被分割的chunk中存在，那么直接引用已存在的chunk，不会再重新产生一个</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：上面的默认配置都添加了注释，一些很简单的配置就不再详细介绍，下面主要介绍一些比较难理解并且重要的配置项。</p>
</blockquote>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>splitChunks</code>默认配置对应的就是 chunk 生成的第二种情况：通过写代码时主动使用<code>import()</code>或者<code>require.ensure</code>来动态加载。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">下面来看下使用<code>import()</code>或者<code>require.ensure</code>来写代码，在 Webpack 打包的时候有什么不同。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">创建<code>index.js</code>，使用<code>import()</code>动态加载<code>react</code>模块，<strong>同时为了方便跟踪产出物，在这里使用了 webpack 的魔法注释，保证输出的 bundle 名称，后面也使用这种方式</strong>。内容如下：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">import</span><span class="token punctuation">(</span><span class="token comment">/* webpackChunkName: "react" */</span> <span class="token string">'react'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：如果忘记魔法注释内容，可以翻阅之前的文章。[TODO]文章链接</p>
</blockquote>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">添加<code>webpack.config.js</code>，内容如下：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">const</span> BundleAnalyzerPlugin <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'webpack-bundle-analyzer'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>BundleAnalyzerPlugin<span class="token punctuation">;</span>
module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    mode<span class="token punctuation">:</span> <span class="token string">'production'</span><span class="token punctuation">,</span>
    entry<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        main<span class="token punctuation">:</span> <span class="token string">'./default/index.js'</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    plugins<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token keyword">new</span> <span class="token class-name">BundleAnalyzerPlugin</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">]</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在这里使用了<a href="https://www.npmjs.com/package/webpack-bundle-analyzer">webpack-bundle-analyzer</a>插件来查看 webpack 打包情况。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">完成上面配置之后，执行<code>webpack --config webpack.config.js</code>，首先看到对应的输出的 log 为：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d074cc80001775213640744.png" alt="图片描述" data-original="http://img.mukewang.com/5d074cc80001775213640744.png" class="" style="cursor: pointer;"><br>
<code>index.js</code>打包出来了两个文件<code>react.js</code>和<code>main.js</code>，两个文件包含的内容通过 webpack-bundle-analyzer 查看效果如下：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d074cf40001f95814260783.png" alt="图片描述" data-original="http://img.mukewang.com/5d074cf40001f95814260783.png" class="" style="cursor: pointer;"><br>
由此可以知道：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;"><code>index.js</code>打包出来了两个文件<code>react.js</code>和<code>main.js</code>；</li>
<li style="font-size: 20px; line-height: 38px;"><code>react.js</code>是被拆分出来的，内容实际是 react；</li>
<li style="font-size: 20px; line-height: 38px;"><code>react.js</code>被拆分出来是因为<code>splitChunks</code>默认配置<code>chunks='async'</code>。</li>
</ol>
</div><div class="cl-preview-section"><h2 id="理解-splitchunks.chunks-三个值" style="font-size: 30px;">理解 <code>splitChunks.chunks</code> 三个值</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>splitChunks</code>中的<code>chunks</code>是一个很重要的配置项，表示从哪些 chunks 里面抽取代码，<code>chunks</code>的三个值有：<code>"initial"</code>、 <code>"all"</code>、 <code>"async"</code>， 默认就是是<code>async</code>。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">为了理解<code>splitChunks.chunks</code>三个值的差异，下面通过实例来帮助我们理解。首先创建两个文件<code>a.js</code>和<code>b.js</code>：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// a.js</span>
<span class="token keyword">import</span> react <span class="token keyword">from</span> <span class="token string">'react'</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> $ <span class="token keyword">from</span> <span class="token string">'jquery'</span><span class="token punctuation">;</span>
<span class="token keyword">import</span><span class="token punctuation">(</span><span class="token comment">/* webpackChunkName: "a-lodash" */</span> <span class="token string">'lodash'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> a <span class="token operator">=</span> <span class="token string">'I am a.js'</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> a<span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// b.js</span>
<span class="token keyword">import</span> $ <span class="token keyword">from</span> <span class="token string">'jquery'</span><span class="token punctuation">;</span>
<span class="token keyword">import</span><span class="token punctuation">(</span><span class="token comment">/* webpackChunkName: "b-react" */</span> <span class="token string">'react'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">import</span><span class="token punctuation">(</span><span class="token comment">/* webpackChunkName: "b-lodash" */</span> <span class="token string">'lodash'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> b <span class="token operator">=</span> <span class="token string">'I am b.js'</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> b<span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：为了方便判断打包出来的 bundle 文件是谁生产的，所以统一使用了魔法注释（magic comments）。</p>
</blockquote>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这两个文件的特点是：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;"><code>react</code>模块被两个文件都引入了，不同的是<code>a.js</code>是同步引入，<code>b.js</code>是动态引入；</li>
<li style="font-size: 20px; line-height: 38px;"><code>jquery</code>模块在两个文件中都被引入，并且<strong>都是同步引入</strong>；</li>
<li style="font-size: 20px; line-height: 38px;"><code>lodash</code>模块都被两个文件引入，并且<strong>都是动态引入</strong>。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">下面是我们的<code>webpack.config.js</code>文件内容，我们主要修改是<code>chunks</code>的三个值：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">const</span> BundleAnalyzerPlugin <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'webpack-bundle-analyzer'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>BundleAnalyzerPlugin<span class="token punctuation">;</span>
module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    mode<span class="token punctuation">:</span> <span class="token string">'development'</span><span class="token punctuation">,</span>
    entry<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        a<span class="token punctuation">:</span> <span class="token string">'./default/a.js'</span><span class="token punctuation">,</span>
        b<span class="token punctuation">:</span> <span class="token string">'./default/b.js'</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    plugins<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token keyword">new</span> <span class="token class-name">BundleAnalyzerPlugin</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
    optimization<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        splitChunks<span class="token punctuation">:</span> <span class="token punctuation">{</span>
            cacheGroups<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                vendors<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                    chunks<span class="token punctuation">:</span> <span class="token string">'async'</span><span class="token punctuation">,</span> <span class="token comment">// 这里是我们修改的地方，async|initial|all</span>
                    test<span class="token punctuation">:</span> <span class="token regex">/[\\/]node_modules[\\/]/</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="chunksasync"><code>chunks='async'</code></h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">当<code>chunks='async'</code>配置下，Webpack 打包 log 和 bundle 分析结果如下：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d074d3a0001e00617240792.png" alt="图片描述" data-original="http://img.mukewang.com/5d074d3a0001e00617240792.png" class="" style="cursor: pointer;"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d074d850001a58214250789.png" alt="图片描述" data-original="http://img.mukewang.com/5d074d850001a58214250789.png" class="" style="cursor: pointer;"><br>
通过实践观察，在这种模式下：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">在<code>a.js</code>和<code>b.js</code> 都同步引入的 <code>jquery</code> 被打包进了各自的 bundle 中没有拆分出来共用，说明在这种配置下只会针对动态引入的的代码进行拆分；</li>
<li style="font-size: 20px; line-height: 38px;"><code>react</code>在<code>a.js</code>和<code>b.js</code>表现不同：
<ol>
<li style="font-size: 20px; line-height: 38px;">在<code>a.js</code>因为是同步引入的，设置的<code>chunks='async'</code>，所以不被拆分出去；</li>
<li style="font-size: 20px; line-height: 38px;">在<code>b.js</code>是动态引入的，符合<code>chunks='async'</code>的设置，所以被单独拆到<code>vendors~b-react.js</code>;</li>
</ol>
</li>
<li style="font-size: 20px; line-height: 38px;"><code>lodash</code>因为在两个文件都是动态加载的，所以被拆到了<code>vendors~a-lodash.js</code>。</li>
</ol>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：<code>b.js</code>中的<code>react</code>拆出来的文件名是<code>vendors~b-react.js</code>含有<code>vendors</code>，说明中了名字为<code>vendors</code>的<code>cacheGroups</code>规则。</p>
</blockquote>
</div><div class="cl-preview-section"><h3 id="chunksinitial"><code>chunks='initial'</code></h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在<code>chunks='initial'</code>配置下，Webpack 打包 log 和 bundle 分析结果如下：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d074dc70001b89b17440792.png" alt="图片描述" data-original="http://img.mukewang.com/5d074dc70001b89b17440792.png" class="" style="cursor: pointer;"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d074e030001785314250787.png" alt="图片描述" data-original="http://img.mukewang.com/5d074e030001785314250787.png" class="" style="cursor: pointer;"><br>
<code>initial</code> 即原始的最初的意思，原则就是有共用的情况即发生拆分。首先，<strong>动态引入的模块不受影响，它是无论如何都会被拆分出去的</strong>。而对于同步引入的代码，如果有多处都在使用，则拆分出来共用，至于共同引用多次会被拆分，是通过<code>minChunks</code>单独配置的，针对这个原则，我们再来看下上面的代码拆分的结果：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">因为<code>jquery</code>模块是<code>a.js</code>和<code>b.js</code>共用的代码，所以单独拆除来放到<code>vendors~a~b.js</code>中，<code>vendors~a~b.js</code>文件名来自我们配置的<code>cacheGroups</code>的 key，即<code>vendors</code>和分隔符（<code>automaticNameDelimiter</code>）以及实际被共用的 bundle 的名称，即：a 和 b；</li>
<li style="font-size: 20px; line-height: 38px;"><code>react</code>在<code>b.js</code>因为用的是动态引入，所以被拆成了<code>b-react.js</code>（名字来自于设置的魔法注释）；<code>a.js</code>的<code>react</code>则被拆到了<code>vendors~a.js</code>；</li>
<li style="font-size: 20px; line-height: 38px;"><code>lodash</code>因为在两个文件都是动态加载的，所以被拆到了<code>a-lodash.js</code>（名字来自魔法注释）。</li>
</ol>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;"><strong>进一步解释</strong>：<code>react</code>在<code>b.js</code>拆出来为<code>b-react.js</code>名称，说明中了默认配置（默认配置是<code>chunks='async'</code>），名字来自魔法注释；<code>a.js</code>的<code>react</code>文件名是<code>vendors~a.js</code>，这是因为中了<code>vendors</code>规则，本身<code>a.js</code>的<code>react</code>是同步引入，在这里被拆出来是因为<code>react</code>在 development 模式用的是 dev 版本，体积超过<code>minSize</code>的默认设置<code>30K</code>，所以被拆出来了，观察对应的 webpack 打包 log：<code>Entrypoint a = vendors~a~b.js vendors~a.js a.js</code> 也说明这一点。如果我们把对应的配置，加大<code>minSize</code>到 80K（超过 dev 版本 react 大小），则<code>vendors~a.js</code> 和 <code>a.js</code>会合并在一起了，具体看下图效果：</p>
</blockquote>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// 忽略其他，只看cacheGroups</span>
vendors<span class="token punctuation">:</span> <span class="token punctuation">{</span>
    minSize<span class="token punctuation">:</span> <span class="token number">80000</span><span class="token punctuation">,</span>
    chunks<span class="token punctuation">:</span> <span class="token string">'initial'</span><span class="token punctuation">,</span>
    test<span class="token punctuation">:</span> <span class="token regex">/[\\/]node_modules[\\/]/</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d07521100018ee516700744.png" alt="图片描述" data-original="http://img.mukewang.com/5d07521100018ee516700744.png" class="" style="cursor: pointer;"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d07526e0001f60414280791.png" alt="图片描述" data-original="http://img.mukewang.com/5d07526e0001f60414280791.png" class="" style="cursor: pointer;"></p>
</div><div class="cl-preview-section"><h3 id="chunksall"><code>chunks='all'</code></h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在 <code>chunks='initial'</code> 配置下，虽然<code>a.js</code>和<code>b.js</code>都引入了<code>react</code>，但是因为引入方式不同，而没有拆分在一起，而是各自单独拆封成一个 chunk，要想把<code>react</code>放到一个文件中，就要使用<code>chunks='all'</code>了。下面是<code>chunks='all'</code>的配置结果：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d0752cc0001072618980744.png" alt="图片描述" data-original="http://img.mukewang.com/5d0752cc0001072618980744.png" class="" style="cursor: pointer;"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d0752ee00015c7314240796.png" alt="图片描述" data-original="http://img.mukewang.com/5d0752ee00015c7314240796.png" class="" style="cursor: pointer;"><br>
通过执行打包结果，跟我们的预期一致，<code>chunks='all'</code>的配置下能够最大程度的生成复用代码，复用代码在 http cache 环境下，多页应用由一个页面跳转到另外一个共用代码的页面，会节省 http 请求，所以一般来说<code>chunks='all'</code>是推荐的方式，但是<code>async</code>和<code>initial</code>也有其存在的必要，理解三者差异，根据项目实际代码拆分需求来配置即可。</p>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：拆分出来的文件名称可以通过<code>output.chunkFilename</code>来指定规则，例如<code>chunkFilename='[name].js'</code>，然后在对应的配置中配置<code>name</code>的具体值，比如 vendors 的 name 指定为<code>foo</code>：<code>vendors.name='foo'</code></p>
</blockquote>
</div><div class="cl-preview-section"><h2 id="使用-cachegroups" style="font-size: 30px;">使用 cacheGroups</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>cacheGroups</code>（缓存组）是 Webpack splitChunks 最核心的配置，<code>splitChunks</code>的配置项都是作用于<code>cacheGroup</code>上的，默认有两个<code>cacheGroup</code>：<code>vendors</code>和<code>default</code>（本文一开始默认配置部分已经贴出），如果将<code>cacheGroup</code>的默认两个分组<code>vendor</code>和<code>default</code>设置为 false，则<code>splitChunks</code>就不会起作用，我们也可以重写这俩默认的配置。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>cacheGroups</code>除了拥有默认配置所有的配置项目（例如 minSize、minChunks、name 等）之外，还有三个独有的配置项：<code>test</code>、<code>priority</code>和<code>reuseExistingChunk</code>。 <code>splitChunks.cacheGroup</code><strong>必须同时满足</strong>各个配置项的条件才能生效</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>reuseExistingChunk</code>表示是否使用已有的 chunk，如果为 true 则表示如果当前的 chunk 包含的模块已经被抽取出去了，那么将不会重新生成新的。下面重点说下<code>test</code>和<code>priority</code></p>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：除了 JavaScript，<code>splitChunks</code>也适用于使用<a href="https://github.com/webpack-contrib/mini-css-extract-plugin">mini-css-extract-plugin</a>插件的 css 配置。</p>
</blockquote>
</div><div class="cl-preview-section"><h3 id="priority">priority</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>priority</code>配置项的意义就是权重。如果有一个模块满足了多个缓存组的条件就会去按照权重划分，谁的权重高就优先按照谁的规则处理。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在下面的配置中：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js">optimization<span class="token punctuation">:</span> <span class="token punctuation">{</span>
    splitChunks<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        cacheGroups<span class="token punctuation">:</span> <span class="token punctuation">{</span>
            vendors<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                chunks<span class="token punctuation">:</span> <span class="token string">'initial'</span><span class="token punctuation">,</span>
                test<span class="token punctuation">:</span> <span class="token regex">/[\\/]node_modules[\\/]/</span><span class="token punctuation">,</span>
                priority<span class="token punctuation">:</span> <span class="token operator">-</span><span class="token number">10</span>
            <span class="token punctuation">}</span><span class="token punctuation">,</span>
            <span class="token keyword">default</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>
                test<span class="token punctuation">:</span> <span class="token regex">/[\\/]node_modules[\\/]/</span><span class="token punctuation">,</span>
                chunks<span class="token punctuation">:</span> <span class="token string">'initial'</span><span class="token punctuation">,</span>
                priority<span class="token punctuation">:</span> <span class="token operator">-</span><span class="token number">20</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">虽然给<code>vendors</code>和<code>default</code>除 priority 配置外，其他配置都相同，打包的结果如下：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d0753360001d76914270793.png" alt="图片描述" data-original="http://img.mukewang.com/5d0753360001d76914270793.png" class="" style="cursor: pointer;"><br>
共用的代码文件名为<code>vendors~cachegroup1~cachegroup2.js</code>说明中了<code>vendors</code>配置，虽然<code>default</code>和<code>vendors</code>两个都能满足需求，但是 <code>default</code> 的 <code>priority</code> 是 <code>-20</code> 明显小于 <code>vendors</code> 的<code>-10</code>，所以会优先按照 vendors 这个缓存组拆分。</p>
</div><div class="cl-preview-section"><h3 id="test">test</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>cacheGroup.test</code>表示满足这个条件的才会被缓存组命中，取值可以是正则、字符串和函数。正则和字符串很好理解，当<code>test</code>为函数时，比如返回<code>true/false</code>，并且接收两个参数：<code>module</code>和<code>chunks</code></p>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;"><code>module</code>：每个模块打包的时候，都会执行<code>test</code>函数，并且传入模块 module 对象，module 对象包含了模块的基本信息，例如类型、路径、文件 hash 等；</li>
<li style="font-size: 20px; line-height: 38px;"><code>chunks</code>：是当前模块被分到哪些<code>chunks</code>使用，module 跟 chunks 关系可能是一对一，也可能是多对一，所以一旦我们使用 chunks 做匹配，那么符合条件的 chunk 内包含的模块都会被匹配到。</li>
</ul>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js">module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment">//...</span>
    optimization<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        splitChunks<span class="token punctuation">:</span> <span class="token punctuation">{</span>
            cacheGroups<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                vendors<span class="token punctuation">:</span> <span class="token punctuation">{</span>
                    <span class="token function">test</span><span class="token punctuation">(</span>module<span class="token punctuation">,</span> chunks<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        <span class="token comment">//...</span>
                        <span class="token keyword">return</span> module<span class="token punctuation">.</span>type <span class="token operator">===</span> <span class="token string">'javascript/auto'</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">举个实际应用场景来说明，前面提到过<code>splitChunks</code>不仅作用于 JavaScript，还可以作用于 CSS，所以类似<code>test=/[\\/]node_modules[\\/]/</code>的写法，实际也会匹配出<code>node_modules</code>中的 CSS，如果我们用到的一个 npm 包引入了自己的 css 文件，那么也会中了拆分逻辑，这时候如果要排除这部分 CSS 或者单独给这部分 CSS 设置自己的<code>cacheGroup</code>规则，有两种方式：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">设置更高权重的<code>cacheGroup</code>；</li>
<li style="font-size: 20px; line-height: 38px;">使用<code>test</code>函数针对类型为 js 和 css 分别设置各自的<code>cacheGroup</code>。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">另外我们还可以使用<code>test</code>函数实现更细化的匹配，例如：忽略一部分文件等。</p>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">本小节 Webpack 相关面试题：</p>
<p style="font-size: 20px; line-height: 38px;">本章节一直在回答一个问题：Webpack 怎么优化。本小节主要介绍 Webpack splitChunks 来拆分代码。</p>
</blockquote>
</div></div>
            </div>
                            <!-- 买过的阅读 -->
                <div class="art-next-prev clearfix">
                                                                        <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/29/article/276">
                                                    <div class="prev l clearfix">
                                <div class="icon l">
                                    <i class="imv2-arrow3_l"></i>
                                </div>
                                <p>
                                    18 Webpack 优化之增强缓存命中率
                                </p>
                            </div>
                        </a>
                                                                                            <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/29/article/278">
                                                    <div class="next r clearfix">
                                <p>
                                    20 Webpack 优化之速度优化
                                </p>
                                <div class="icon r">
                                    <i class="imv2-arrow3_r"></i>
                                </div>

                            </div>
                        </a>
                                    </div>
                    </div>
        <div class="comments-con js-comments-con" id="coments_con">     <div class="number">精选留言 <span class="js-number">0</span></div>     <div class="comments">         <div class="input-fake js-showcommentModal">             欢迎在这里发表留言，作者筛选后可公开显示         </div>                      <div class="noData">                 <p>                     <i class="imv2-error_c"></i>                 </p>                 <p>目前暂无任何讨论</p>             </div>              </div>  </div>



    </div>
    
    
    

</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>